<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="宗亲名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入宗亲名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input
            v-model="queryParams.location"
            placeholder="请输入位置"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- <div class="mb-10px" v-if="pageData.length < 1"> -->
      <div class="mb-10px" v-if="pageData.length < 1">
        <el-button
          v-hasPerm="['clan:clan-association:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['clan:clan-association:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="ID"
          prop="id"
          min-width="80"
          align="center"
        />
        <el-table-column
          key="familyName"
          label="家谱名称"
          prop="familyName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="name"
          label="协会名称"
          prop="name"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="location"
          label="位置"
          prop="location"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="history"
          label="简介"
          prop="history"
          min-width="200"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          key="qrcodeUrl"
          label="二维码"
          prop="qrcodeUrl"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <el-image
              v-if="scope.row.qrcodeUrl"
              :src="scope.row.qrcodeUrl"
              style="width: 50px; height: 50px"
              :preview-src-list="[scope.row.qrcodeUrl]"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenInfo(scope.row.id)"
            >
            <template #icon><Edit /></template>
              详情
            </el-button>
            <el-button
              v-hasPerm="['clan:clan-association:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['clan:clan-association:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 宗族协会表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="宗亲会名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入宗亲会名称"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="位置" prop="location">
          <el-input
            v-model="formData.location"
            placeholder="请输入位置"
            show-word-limit
            disabled
          />
        </el-form-item>

        <el-form-item label="地理位置">
          <div class="map-container">
            <div id="map-container" class="amap-wrapper"></div>
            <div class="map-info">
              <p>经度: {{ formData.longitude || '未设置' }}</p>
              <p>纬度: {{ formData.latitude || '未设置' }}</p>
              <el-button type="primary" size="small" @click="showMapDialog = true">
                选择位置
              </el-button>
            </div>
          </div>

          <el-dialog v-model="showMapDialog" title="选择位置" width="80%" :destroy-on-close="true">
            <div class="map-search-container">
              <el-input 
                v-model="searchAddress" 
                placeholder="输入地址搜索位置" 
                @input="searchLocation" 
                clearable  
                @keyup.enter="searchLocation"
              >
                <template #append>
                  <el-button @click="searchLocation">
                    <el-icon>
                      <Search />
                    </el-icon>
                  </el-button>
                </template>
              </el-input>
              <div v-if="searchResults.length > 0" class="search-results">
                <div 
                  v-for="(item, index) in searchResults" 
                  :key="index" 
                  class="search-result-item"
                  @click="useSearchResult(item)"
                >
                  {{ item.formattedAddress }}
                </div>
              </div>
            </div>
            <div style="height: 500px">
              <div id="map-dialog" style="height: 100%"></div>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showMapDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmLocation">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </el-form-item>

        <el-form-item label="简介" prop="history">
          <WangEditor v-model="formData.history" style="min-height: 200px;" />
        </el-form-item>

        <el-form-item label="收款码" prop="qrcodeUrl">
          <SingleImageUpload
            v-model="formData.qrcodeUrl"
            :max-file-size="2"
            :accept="'.jpg,.jpeg,.png,.gif'"
            :style="{ width: '180px', height: '180px' }"
          />
          <div class="upload-tip">请上传微信或支付宝收款码，大小不超过2MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: "ClanAssociationManage",
  inheritAttrs: false,
});

import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus, Delete, Edit } from "@element-plus/icons-vue";
import ClanAssociationAPI from "@/api/clan/clan-association";
import WangEditor from "@/components/WangEditor/index.vue";
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";

const router = useRouter();

const queryFormRef = ref();
const dataFormRef = ref();
const dataTableRef = ref();

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
  location: "",
});

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive({
  id: undefined,
  name: "",
  location: "",
  history: "",
  qrcodeUrl: "",
  createTime: "",
  updateTime: "",
  createBy: "",
  updateBy: "",
  longitude: null,
  latitude: null,
});

const rules = reactive({
  name: [{ required: true, message: "请输入协会名称", trigger: "blur" }],
  location: [{ required: true, message: "请输入位置", trigger: "blur" }],
});

// 地图相关变量
const showMapDialog = ref(false);
let map = null;
let dialogMap = null;
let marker = null;
let tempLocation = { lng: null, lat: null };
const searchAddress = ref('');
const searchResults = ref([]);
const AMAP_WEB_API_KEY = '9c5a053254c95d14843efc080ac74f78';
const AMAP_SECURITY_CODE = '59173e03758c881beab7c813d3a25329';

// 查询宗族协会列表
function handleQuery() {
  loading.value = true;
  ClanAssociationAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .catch((error) => {
      console.log(1231231)
      console.error("获取宗族协会列表失败:", error);
      ElMessage.error("获取宗族协会列表失败");
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行复选框选中项变化
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

// 打开宗族协会弹窗
function handleOpenDialog(id) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改宗族协会";
    ClanAssociationAPI.getFormData(id)
      .then((data) => {
        Object.assign(formData, data);
      })
      .catch((error) => {
        console.error("获取宗族协会详情失败:", error);
        ElMessage.error("获取宗族协会详情失败");
      });
  } else {
    dialog.title = "新增宗亲会";
    resetForm();
  }
}

// 宗族协会表单提交
function handleSubmit() {
  console.log(formData)
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ClanAssociationAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .catch((error) => {
            console.error("修改宗族协会失败:", error);
            ElMessage.error("修改宗族协会失败");
          })
          .finally(() => (loading.value = false));
      } else {
        ClanAssociationAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .catch((error) => {
            console.error("新增宗族协会失败:", error);
            ElMessage.error("新增宗族协会失败");
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 重置表单
function resetForm() {
  dataFormRef.value?.resetFields();
  dataFormRef.value?.clearValidate();
  Object.assign(formData, {
    id: undefined,
    name: "",
    location: "",
    history: "",
    qrcodeUrl: "",
    createTime: "",
    updateTime: "",
    createBy: "",
    updateBy: "",
    longitude: null,
    latitude: null,
  });
}
function handleOpenInfo(id) {
  // 跳转到宗亲会详情页
  // 跳转路由并传递id参数
  router.push({ path: '/genealogy/member/managesa', query: { id } })
}
// 关闭宗族协会弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

// 删除宗族协会
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除该项宗族协会?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      ClanAssociationAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .catch((error) => {
          console.error("删除宗族协会失败:", error);
          ElMessage.error("删除宗族协会失败");
        })
        .finally(() => (loading.value = false));
    })
    .catch(() => {
      // 用户取消删除
    });
}

// 地图相关方法
// 加载高德地图脚本
function loadAMap() {
  return new Promise((resolve, reject) => {
    window._AMapSecurityConfig = { securityJsCode: AMAP_SECURITY_CODE };
    if (window.AMap) return resolve(window.AMap);
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_WEB_API_KEY}&plugin=AMap.Geocoder`;
    script.async = true;
    script.onload = () => resolve(window.AMap);
    script.onerror = (error) => reject(error);
    document.head.appendChild(script);
  });
}

// 初始化地图
function initMap() {
  if (!document.getElementById('map-container')) return;
  if (!window.AMap) {
    loadAMap().then(() => setTimeout(() => initMap(), 500));
    return;
  }
  map = new AMap.Map('map-container', {
    zoom: 11,
    resizeEnable: true,
    center: [formData.longitude || 116.397428, formData.latitude || 39.90923]
  });
  if (formData.longitude && formData.latitude) {
    marker = new AMap.Marker({
      position: [formData.longitude, formData.latitude],
      map: map
    });
    map.setCenter([formData.longitude, formData.latitude]);
  }
}

// 初始化对话框地图
function initDialogMap() {
  if (!document.getElementById('map-dialog')) return;
  if (!window.AMap) {
    loadAMap().then(() => setTimeout(() => initDialogMap(), 500));
    return;
  }
  dialogMap = new AMap.Map('map-dialog', {
    zoom: 11,
    resizeEnable: true,
    center: [formData.longitude || 116.397428, formData.latitude || 39.90923]
  });
  if (formData.longitude && formData.latitude) {
    dialogMap.setCenter([formData.longitude, formData.latitude]);
    tempLocation = {
      lng: formData.longitude,
      lat: formData.latitude
    };
    new AMap.Marker({
      position: [formData.longitude, formData.latitude],
      map: dialogMap
    });
  }
  dialogMap.on('click', function(e) {
    dialogMap.clearMap();
    new AMap.Marker({
      position: [e.lnglat.getLng(), e.lnglat.getLat()],
      map: dialogMap
    });
    tempLocation = {
      lng: e.lnglat.getLng(),
      lat: e.lnglat.getLat()
    };
    getAddressFromLocation(e.lnglat.getLng(), e.lnglat.getLat());
  });
}

// 通过经纬度获取地址
function getAddressFromLocation(lng, lat) {
  if (!window.AMap) return;
  const geocoder = new AMap.Geocoder({ city: '全国' });
  geocoder.getAddress([lng, lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      if (result.regeocode && result.regeocode.formattedAddress) {
        formData.location = result.regeocode.formattedAddress;
        formData.longitude = lng;
        formData.latitude = lat;
      }
    } else {
      formData.location = `坐标位置(${lng.toFixed(6)}, ${lat.toFixed(6)})`;
      formData.longitude = lng;
      formData.latitude = lat;
    }
  });
}

// 确认位置选择
function confirmLocation() {
  if (tempLocation.lng && tempLocation.lat) {
    formData.longitude = tempLocation.lng;
    formData.latitude = tempLocation.lat;
    if (map) {
      map.clearMap();
      marker = new AMap.Marker({
        position: [tempLocation.lng, tempLocation.lat],
        map: map
      });
      map.setCenter([tempLocation.lng, tempLocation.lat]);
    }
  }
  showMapDialog.value = false;
}

// 搜索地址
function searchLocation() {
  if (!searchAddress.value || !window.AMap) return;
  AMap.plugin('AMap.Geocoder', function() {
    const geocoder = new AMap.Geocoder({ city: '全国' });
    geocoder.getLocation(searchAddress.value, function(status, result) {
      if (status === 'complete' && result.info === 'OK') {
        console.log(result.geocodes)
        if (result.geocodes && result.geocodes.length > 0) {
          searchResults.value = result.geocodes;
          if (result.geocodes.length === 1) {
            useSearchResult(result.geocodes[0]);
          }
        } else {
          ElMessage.warning('未找到匹配的地址');
          searchResults.value = [];
        }
      } else {
        ElMessage.error('地址搜索失败');
        searchResults.value = [];
      }
    });
  });
}

// 使用搜索结果
function useSearchResult(item) {
  if (!dialogMap || !item || !item.location) return;
  const location = item.location;
  tempLocation = { lng: location.lng, lat: location.lat };
  dialogMap.clearMap();
  new AMap.Marker({ position: [location.lng, location.lat], map: dialogMap });
  dialogMap.setCenter([location.lng, location.lat]);
  dialogMap.setZoom(15);
  formData.location = item.formattedAddress;
  formData.longitude = location.lng;
  formData.latitude = location.lat;
  searchResults.value = [];
}

// 监听地图弹窗打开，初始化地图
watch(showMapDialog, (newVal) => {
  if (newVal) {
    nextTick(() => {
      setTimeout(() => {
        if (window.AMap) {
          initDialogMap();
        } else {
          loadAMap().then(() => initDialogMap());
        }
      }, 500);
    });
  } else {
    searchAddress.value = '';
    searchResults.value = [];
  }
});

// 监听对话框打开，初始化地图
watch(() => dialog.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      setTimeout(() => {
        if (window.AMap) {
          initMap();
        } else {
          loadAMap().then(() => initMap());
        }
      }, 500);
    });
  }
});

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 16px;
}

.mb-10px {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.map-container {
  display: flex;
}

.map-info {
  margin-left: 20px;
}

.amap-wrapper {
  width: 300px;
  height: 200px;
  border: 1px solid #ddd;
  position: relative;
  overflow: hidden;
}

.map-search-container {
  margin-bottom: 10px;
}

.search-results {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-top: none;
  background: white;
}

.search-result-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.search-result-item:hover {
  background-color: #f5f5f5;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}
</style>
